//
//  HelloWorldLayer.m
//  Memory Mania
//
//  Created by Sanket Karkhanis on 2/14/12.
//  Copyright University of Southern California 2012. All rights reserved.
//


// Import the interfaces
#import "HelloWorldLayer.h"
#import "ModeSelect.h"
#import "GlobalData.h"
#import "GameOver.h"



// HelloWorldLayer implementation
@implementation HelloWorldLayer


+(CCScene *) scene
{
   // value1=row;
	// 'scene' is an autorelease object.
	CCScene *scene = [CCScene node];
	
	// 'layer' is an autorelease object.
	HelloWorldLayer *layer = [HelloWorldLayer node];
    
	// add layer as a child to scene
	[scene addChild: layer];
	
	// return the scene
	return scene;
}

// on "init" you need to initialize your instance
-(id) init
{
	// always call "super" init
	// Apple recommends to re-assign "self" with the "super" return value
	if((self=[super init])) {
        CCSprite *HWLbg = [CCSprite spriteWithFile:@"ecstaticist-sunkissed.jpg"];
		HWLbg.anchorPoint = ccp(0.5,0.5);      
        HWLbg.position = ccp(500,350);
		//bg.opacity = 100;        
        [self addChild:HWLbg z:0 tag:1];
        
        //the small menu button one the bottom left
        
        //CCMenuItem *Back = [CCMenuItemFont itemFromString:@"Back" target:self selector:@selector(onBack:)]; 
        //Menu = [CCMenu menuWithItems: Back, nil];
        //Menu.position = ccp(50,40);
        //[Menu alignItemsVerticallyWithPadding:100.0f];
        //[self addChild:Menu];
        
        //addiing the banner
        
        
        CCSprite *banner1 = [CCSprite spriteWithFile:@"Straight-Line.jpg"];
        banner1.position = ccp(100,350);
        banner1.scaleX = 2.0f;
        banner1.scaleY = 5.0f;
        
        CCSprite *banner2 = [CCSprite spriteWithFile:@"Straight-Line.jpg"];
        banner2.position = ccp(924,350);
        banner2.scaleX = 2.0f;
        banner2.scaleY = 5.0f;
        
        [self addChild:banner1 z:1];         
        [self addChild:banner2 z:1]; 
        
        
        CCLabelTTF *Tag_Score = [CCLabelTTF labelWithString:@"Score" fontName:@"Arial" fontSize:30];      
        Tag_Score.position = ccp(50,730);
        [self addChild: Tag_Score z:1];  
        
        CCLabelTTF *Tag_Player1 = [CCLabelTTF labelWithString:@"Player1" fontName:@"Arial" fontSize:30];
        Tag_Player1.position = ccp(180,730);
        [self addChild: Tag_Player1 z:1];  
        
        //intialize the first score label
        scoreLabel1 = [CCLabelBMFont labelWithString:@"0" fntFile:@"font09.fnt"];
        scoreLabel1.scale = 1.3;
        //scoreLabel1.anchorPoint = ccp(0.2,0.2);
        scoreLabel1.position = ccp(270,730);        
        [self addChild:scoreLabel1];        
        
        CCLabelTTF *Tag_Player2 = [CCLabelTTF labelWithString:@"Player2" fontName:@"Arial" fontSize:30];
        Tag_Player2.position = ccp(380,730);
        [self addChild: Tag_Player2 z:1];        
        
        
        //intialize the second score label       
        scoreLabel2 = [CCLabelBMFont labelWithString:@"0" fntFile:@"font09.fnt"];
        scoreLabel2.scale = 1.3;
        //scoreLabel2.anchorPoint = ccp(0.2,0.2);
        scoreLabel2.position = ccp(470,730);        
        [self addChild:scoreLabel2];
        
        rows = [GlobalData sharedGlobalData].rows;
        cols = [GlobalData sharedGlobalData].cols;
        NSLog(@"The Current rows = %i  and cols = %i", rows, cols);
		self.isTouchEnabled=YES;
        click_count=0;
        selectedcard1=0;
        selectedcard2=0;
        size = rows*cols;
        totalMatched =0;
        //intialize the score of the first player to be 0
        [GlobalData sharedGlobalData].score1 = 0;
        [GlobalData sharedGlobalData].score2 = 0;
        //Initializing all card positions on screen for  4*5
        
        if(size == 20)
            
        {
            
            for(int i=0; i<5; i++)
                
            {
                
                posOnScreen20[i]= CGPointMake(100+(200*i),150);
                
                posOnScreen20[i+5]= CGPointMake(100+(200*i),300);
                
                posOnScreen20[i+10]= CGPointMake(100+(200*i),450);
                
                posOnScreen20[i+15]= CGPointMake(100+(200*i),600);
                
            }
            
        }
        
        
        
        //Initializing all card positions on screen for 4*4         
        
        if(size ==16)
            
        {
            
            for(int i=0;i<4;i++)
                
            {
                
                posOnScreen16[i]= CGPointMake(180 +(220*i), 150);
                
                posOnScreen16[i+4]= CGPointMake(180 +(220*i), 300);
                
                posOnScreen16[i+8]= CGPointMake(180 +(220*i), 450);
                
                posOnScreen16[i+12] = CGPointMake(180 + (220*i), 600);
                
            }
            
        }
        
        
        
        //Intializing all card positions on screen for 4*3
        
        if(size==12)
            
        {
            
            for(int i=0;i<3;i++)
                
            {
                
                posOnScreen12[i] = CGPointMake(220 + (250*i), 150);
                
                posOnScreen12[i+3]= CGPointMake(220 + (250*i),300);
                
                posOnScreen12[i+6]= CGPointMake(220+ (250*i), 450);
                
                posOnScreen12[i+9]= CGPointMake(220+ (250*i), 600);
                
            }
            
        }
        
        
        for (int i=0; i<size; i++)
            
        {
            
            cover[i]=[[CCSprite spriteWithFile:@"white.jpg"] retain];
            cover[i].scale=0.28;
            [self addChild:cover[i] z:5];
        }
        
        //Initializing numbersGenerated Array for keeping track of random nos generated
        
        for(int i=0;i<size;i++)
            numbersGenerated[i]=NO;
        
        //JUST A PRECAUTION NOT REQ!
        
        for(int a=size; a<20-size; a++)
            numbersGenerated[a]=YES; 
        
        cards[0]= [CCSprite spriteWithFile:@"tick.jpeg"];
        [self addChild:cards[0] z:0 tag:0];       
        
        cards[1]= [CCSprite spriteWithFile:@"tick.jpeg"];
        [self addChild:cards[1] z:0 tag:0];
        
        
        
        cards[2]= [CCSprite spriteWithFile:@"cross.png"];
        [self addChild:cards[2] z:0 tag:1];        
        
        cards[3]= [CCSprite spriteWithFile:@"cross.png"];
        [self addChild:cards[3] z:0 tag:1];
        
        
        
        cards[4]= [CCSprite spriteWithFile:@"message.png"];
        [self addChild:cards[4] z:0 tag:2];
        
        cards[5]= [CCSprite spriteWithFile:@"message.png"];
        [self addChild:cards[5] z:0 tag:2];
        
        
        cards[6]= [CCSprite spriteWithFile:@"exclamation.png"];
        [self addChild:cards[6] z:0 tag:3];        
        
        cards[7]= [CCSprite spriteWithFile:@"exclamation.png"];
        [self addChild:cards[7] z:0 tag:3];
        
        
        cards[8]= [CCSprite spriteWithFile:@"Notes.png"];
        [self addChild:cards[8] z:0 tag:4];
        
        cards[9]= [CCSprite spriteWithFile:@"Notes.png"];
        [self addChild:cards[9] z:0 tag:4];
        
        
        cards[10]= [CCSprite spriteWithFile:@"musicplayer.png"];
        [self addChild:cards[10] z:0 tag:5];
        
        cards[11]= [CCSprite spriteWithFile:@"musicplayer.png"];
        [self addChild:cards[11] z:0 tag:5];
        
        
        
        cards[12]= [CCSprite spriteWithFile:@"Full Trash.png"];
        [self addChild:cards[12] z:0 tag:6];
        
        cards[13]= [CCSprite spriteWithFile:@"Full Trash.png"];
        [self addChild:cards[13] z:0 tag:6];
        
        
        
        cards[14]= [CCSprite spriteWithFile:@"calculator-1.png"];
        [self addChild:cards[14] z:0 tag:7];
        
        cards[15]= [CCSprite spriteWithFile:@"calculator-1.png"];
        [self addChild:cards[15] z:0 tag:7];
        
        
        cards[16]= [CCSprite spriteWithFile:@"error.jpg"];
        [self addChild:cards[16] z:0 tag:8];
        
        cards[17]= [CCSprite spriteWithFile:@"error.jpg"];
        [self addChild:cards[17] z:0 tag:8];
        
        
        cards[18]= [CCSprite spriteWithFile:@"copy.png"];
        [self addChild:cards[18] z:0 tag:9];
        
        cards[19]= [CCSprite spriteWithFile:@"copy.png"];
        [self addChild:cards[19] z:0 tag:9];
        
        for(int a=0; a<20; a++)
            cards[a].visible=NO;
        
        for(int i=0; i<size; i++)
            
        {
            
            //cards[i].position = [self putCard:size]; 
            
            CGPoint p = CGPointMake(0, 0);
            
            p = [self putCard:size];
            
            cards[i].position = p;
            
            cover[i].position = p;
            
            cards[i].scale = 0.45;
            cards[i].visible= YES;
            
            // cover[i].position=cards[i].position;        
            
            
            
        }
        
	}
    //TIME STUFF
    
    CGSize size1 = [[CCDirector sharedDirector] winSize];
    
    
    
    //set time to zero
    
    myTime = 0;
    
    
    
    timeLabel = [CCLabelTTF labelWithString:@"0" fontName:@"Arial" fontSize:48];
    
    timeLabel.position = CGPointMake(880, size1.height-10);
    
    // Adjust the label's anchorPoint's y position to make it align with the top.
    
    timeLabel.anchorPoint = CGPointMake(0.5f, 1.0f);
    
    // Add the time label
    
    [self addChild:timeLabel];
    
    //update
    
    [self schedule:@selector(update:)];
    

	return self;
}


-(CGPoint)putCard:(int) size2
{
    int r = arc4random() % size2;
    if(numbersGenerated[r]==NO)
    {
        numbersGenerated[r]=YES;
    }
    else
    {
        while(numbersGenerated[r]==YES)
            r=(r+1)%size2;
        numbersGenerated[r]=YES;
    }
    CCLOG(@"RANDOM GENERATED = %i", r);
    CGPoint p= CGPointMake(0, 0);
    if(size2==20)
    {
        p=posOnScreen20[r];
        CCLOG(@"Position = %f , %f", p.x,p.y); 
        return p;
        // return posOnScreen20[r];
    }
    if(size2==16)
    {
        p=posOnScreen16[r];
        CCLOG(@"Position = %f , %f", p.x,p.y);
        return p;
        //return posOnScreen16[r];
    }
    else
    {
        //if(size==12)
        p=posOnScreen12[r];
        CCLOG(@"Position = %f , %f", p.x,p.y);
        return p;
        //return posOnScreen12[r];
    }
    
}






-(void) coverCard:(ccTime) dt {
    cover[selectedcard1].visible=YES;
    cover[selectedcard2].visible=YES;
    CCLOG(@"card1: %i, card2: %i, count: %i",selectedcard1, selectedcard2, click_count);
    [self unschedule:@selector(coverCard:)];
    selectedcard1=0;
    selectedcard2=0;
    click_count=0;
}

-(void) removeCards:(ccTime) dt{

    //[cards[selectedcard1] runAction:[CCScaleBy actionWithDuration:0.2 scale:0.5]];
    //[cards[selectedcard2] runAction:[CCScaleBy actionWithDuration:0.2 scale:0.5]];
    cards[selectedcard1].visible=NO;
    cards[selectedcard2].visible=NO;
    cover[selectedcard1].visible=NO;
    cover[selectedcard2].visible=NO;
    [self unschedule:@selector(removeCards:)];
    selectedcard1=0;
    selectedcard2=0;
    click_count=0;
    totalMatched+=2;
    
    // successfully remove a pair of cards +100 points
    [GlobalData sharedGlobalData].score1 += 100;
    [GlobalData sharedGlobalData].score2 += 100;
    
    // change the score display on gameplay
    [scoreLabel1 setString:[NSString stringWithFormat:@"%d",[GlobalData sharedGlobalData].score1]];
    [scoreLabel2 setString:[NSString stringWithFormat:@"%d",[GlobalData sharedGlobalData].score2]];
    
    if(totalMatched==size)
        [[CCDirector sharedDirector] replaceScene:[GameOver node]];
    
}

-(void) ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint loc = [touch locationInView:[touch view]];
    loc=[[CCDirector sharedDirector]convertToGL:loc];
    for (int i=0; i<size; i++) {
        if(click_count!=2 && CGRectContainsPoint([cards[i] boundingBox], loc))
        {   
            click_count++;
            if (click_count==1) {
                selectedcard1=i;
            }
            else if(click_count==2){
                selectedcard2=i;
            }
           
            cover[i].visible=NO;
            if(click_count==2)
            {
                if(selectedcard1!=selectedcard2 && cards[selectedcard1].tag==cards[selectedcard2].tag)
                 {

                   [self schedule:@selector(removeCards:) interval:2 ];
                     
                     
                 }
                else if(selectedcard1!=selectedcard2){
                   [self schedule:@selector(coverCard:) interval:2 ]; 
                }
                else{
                    click_count--;
                }
                
                
            }
        }
        
    }
   
    
}

-(void)update:(ccTime)dt{
    
    totalTime += dt;
    currentTime = (int)totalTime;
	if (myTime < currentTime)
	{
		myTime = currentTime;
		//[timeLabel setString:[NSString stringWithFormat:@"%i", myTime]];
        
        [timeLabel setString:[NSString stringWithFormat:@"%02d:%02d", myTime/60, myTime%60]];
    }
}


-(void) onHighscore: (id) sender
{
    
}
// on "dealloc" you need to release all your retained objects
- (void) dealloc
{
	// in case you have something to dealloc, do it in this method
	// in this particular example nothing needs to be released.
	// cocos2d will automatically release all the children (Label)
	
	// don't forget to call "super dealloc"
	[super dealloc];
}
@end
